﻿using System;

using Gonte.Reflection;
using Gonte.UI;

namespace Gonte.Wpf.Controls.ViewModel
{
    public class ItemObjectViewModelInfo
        : ItemViewModelInfo
    {
        #region Constructors

        internal ItemObjectViewModelInfo(Type type)
        {
            _type = type;
        } 

        #endregion

        public static ItemViewModelInfo GetInfo(Type type)
        {
            ExceptionThrower.ThrowWhenNull("type", type);

            UserInterfaceAttribute uiAttribute = CustomAttribute.GetCustomAttribute<UserInterfaceAttribute>(type, false);

            ExceptionThrower.ThrowWhenNull("viewModelAttribute", uiAttribute);
            ExceptionThrower.ThrowWhenNullOrEmpty("viewModelAttribute.LabelProperty", uiAttribute.LabelProperty);

            string viewModelInfoName = type.FullName;

            if (!_viewModelInfos.ContainsKey(viewModelInfoName))
            {
                ItemViewModelInfo viewModelInfo = CreateViewModelInfo(type);
                viewModelInfo.Populate();
                AddViewModelInfo(viewModelInfoName, viewModelInfo);

                return viewModelInfo;
            }

            return _viewModelInfos[viewModelInfoName];
        }

        internal override void Populate()
        {
            UserInterfaceAttribute viewModelAttribute = CustomAttribute.GetCustomAttribute<UserInterfaceAttribute>(_type, false);
            ExceptionThrower.ThrowWhenNull("viewModelAttribute", viewModelAttribute);

            // Set the label
            LabelProperty = viewModelAttribute.LabelProperty;

            ExceptionThrower.ThrowWhenNullOrEmpty("viewModelAttribute.LabelProperty", LabelProperty);

            IconUri = viewModelAttribute.IconUri;
        }

        #region Helpers

        private static ItemViewModelInfo CreateViewModelInfo(Type type)
        {
            UserInterfaceItemAttribute[] childrenAttributes = CustomAttribute.GetCustomAttributes<UserInterfaceItemAttribute>(type, false);

            if (childrenAttributes != null)
            {
                return new ContentObjectViewModelInfo(type);
            }
            // else
            return new ItemObjectViewModelInfo(type);
        } 

        #endregion

        #region Fields

        private Type _type;
        internal string LabelProperty;

        #endregion
    }
}
